import { SlideRef } from "@shared/slide";
import React from "react";
import styles from "@pages/personal/styles/styles.module.less";
import Header from "@shared/header";
import GeekIcon from "@shared/geekIcon";
import Textarea from "react-textarea-autosize";
import { useUpdateProfileMutation } from "@service/user";
import Loading from "@shared/loading";
import toast from "react-hot-toast";
import { useEffect, useState, ChangeEvent } from "react";


interface Props {
    intro: string;
    slideRef: React.RefObject<SlideRef | null>;
}

export default function UpdateIntro({ intro, slideRef }: Props) {
    const [text, setText] = useState(intro || "");
    // 用于修改用户简介
    const [updateProfile, { isLoading, isSuccess }] = useUpdateProfileMutation();

    // 更新用户在文本域中输入的内容
    const updateText = (event: ChangeEvent<HTMLTextAreaElement>) => {
        // 获取用户在文本域中输入的内容
        const value = event.currentTarget.value;
        // 判断内容是否超出限制
        if (value.length <= 100) {
            // 没有超出限制, 将用户在文本域中输入的内容同步到组件状态
            setText(value);
        }
    };

    // 监听用户简介是否修改成功
    useEffect(() => {
        // 修改成功
        if (isSuccess) {
            // 用户提示
            toast.success("用户简介修改成功");
            // 关闭弹框
            slideRef.current?.close();
        }
    }, [isSuccess, slideRef]);

    return (
        <div className={styles.content}>
            <Header
                title={"编辑简介"}
                left={
                    <GeekIcon
                        type={"iconfanhui"}
                        className={styles.icon}
                        onClick={slideRef.current?.close}
                    />
                }
                right={<button onClick={() => updateProfile({ intro: text })}>提交</button>} />
            <form>
                <div className={styles.bg}>
                    <Textarea value={text} onChange={updateText} placeholder={"请输入用户简介"}></Textarea>
                    <div className={styles.count}>{text.length}/100</div>
                </div>
            </form>
            {isLoading && <Loading />}
        </div>


    );
}
